﻿using System;
using System.Collections.Generic;
using System.Linq;

using Moe.ECamel.Common.Entities;

namespace Moe.ECamel.Server.BL
{
	public class InventoryBL : ECamelBL
	{
		public InventoryBL(ECamelDataContext dataContext)
			: base(dataContext)
		{
		}

		public void AddInventoryList(IEnumerable<Inventory> inventoryList)
		{
			foreach (var inventory in inventoryList)
				dataContext.Inventories.InsertOnSubmit(inventory);
		}

		public Inventory GetAvailableInventory(int libraryId, int itemId)
		{
			var query = from i in dataContext.Inventories
			            where i.ItemId == itemId && i.LibraryId == libraryId && i.IsAvailable
			            select i;

			return query.FirstOrDefault();
		}

		public Inventory FindTransferrableCopy(int itemId, Library targetLibrary)
		{
			var inventory = (from i in dataContext.Inventories									// Find an inventory 
							 where i.ItemId == itemId &&										// Of the requested item
							  i.IsAvailable &&													// Which is available
							  i.LibraryId != targetLibrary.LibraryId &&							// And belongs to a different library
							  Equals(i.Library.ParentLibraryId, targetLibrary.ParentLibraryId)	// And belongs to a library whose parent is the same as the requested library's parent.
							select i).FirstOrDefault();
			
			return inventory;
		}

		public void AddInventoryRequest(int itemId, int libraryId, DateTime requestDate)
		{
			var inventoryRequest = new InventoryRequest { ItemId = itemId, LibraryId = libraryId, RequestDate = requestDate, Active = true};
			dataContext.InventoryRequests.InsertOnSubmit(inventoryRequest);
		}

		public IList<InventoryRequest> GetActiveInventoryRequests(int itemId, int libraryId)
		{
			return (from ir in dataContext.InventoryRequests
					where ir.ItemId == itemId && ir.LibraryId == libraryId && ir.Active
					select ir).ToList();
		}

		public Inventory GetInventory(int inventoryId)
		{
			return (from i in dataContext.Inventories 
					where i.InventoryId == inventoryId
					select i).SingleOrDefault();
		}
	}
}